package com.atguigu.daijia.driver.config;

import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;


@Component
public class QiniuKodoUtil  {  //读取配置文件中七牛云的属性
    Configuration cfg = new Configuration(Region.region2());
    @Value("${qiniu.kodo.accessKey}")
    String accessKey;
    @Value("${qiniu.kodo.secretKey}")
    String secretKey;
    @Value("${qiniu.kodo.bucket}")
    String bucket;
    @Value("${qiniu.kodo.domain}")
    String domain;

    /**
     * 上传文件
     * @param file
     * @param path
     * @return
     */
    public CosUploadVo upload(MultipartFile file, String path) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region1());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本

        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //文件后缀名
        String uploadPath = "driver/" + path + "/" + UUID.randomUUID().toString().replaceAll("-", "") + fileType;

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(file.getBytes(), uploadPath, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            StringBuffer stringBuilder = new StringBuffer("http://sljoghone.hb-bkt.clouddn.com/");
            stringBuilder
                    .append(uploadPath);

            CosUploadVo cosUploadVo = new CosUploadVo();
            cosUploadVo.setUrl(uploadPath);
            //  图片临时访问url，回显使用
            cosUploadVo.setShowUrl(getShowUrl(uploadPath));
            return cosUploadVo;
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
            return null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 临时访问url
     * @param uploadPath
     * @return
     */
    public String getShowUrl(String uploadPath) {
        String domainOfBucket = "http://"+domain;
        String encodedFileName = null;
        try {
            encodedFileName = URLEncoder.encode(uploadPath, "utf-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        Auth auth = Auth.create(accessKey, secretKey);
        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
        return auth.privateDownloadUrl(publicUrl, expireInSeconds);
    }
}